package com.bnz.listener;

import com.bnz.pojo.Product;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class MyApplicationListener implements ServletContextListener, ServletContextAttributeListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 1. 得到当前的应用程序对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        //  2. 构造所有的商品列表
        Product p1 = new Product("1001", "双飞燕鼠标", 98.0f, 100);
        Product p2 = new Product("1002", "联想电脑", 3998.0f, 500);
        Product p3 = new Product("1003", "海尔洗衣机", 1200.0f, 200);
        Product p4 = new Product("1004", "海飞丝洗发水", 45.0f, 80);
        Product p5 = new Product("1005", "IPhone平板", 3000.0f, 300);
        Product p6 = new Product("1006", "焦糖瓜子", 5.0f, 200);
        // 3. 构造一个Map对象
        Map<String,Product> productMap = new HashMap<>();
        // 4. 将所有的商品放到Map对象中
        productMap.put(p1.getPid(),p1);
        productMap.put(p2.getPid(),p2);
        productMap.put(p3.getPid(),p3);
        productMap.put(p4.getPid(),p4);
        productMap.put(p5.getPid(),p5);
        productMap.put(p6.getPid(),p6);
        // 5. 将Map放到servletContext对象中
        servletContext.setAttribute("products",productMap);
    }


    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("应用程序销毁");
    }
    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("为应用程序添加属性");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("从应用程序中移除属性");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {

    }
}
